<template>
    <myDialog :visible="popupFlag">
        <div style="padding: 70px 0;">
            <div class="main" @click.stop>
                <div class="header flex">
                    <div class="title_box flex">
                        <img src="../../assets/fileFlow_label.png" style="margin-right: 10px;">
                        <p v-if="addFileForm.id">修改公文</p>
                        <p v-else>发布公文</p>
                    </div>
                    <el-icon @click="closeHandle">
                        <Close />
                    </el-icon>
                </div>


                <div class="row flex">
                    <div class="input_box">
                        <p class="pTitle"><span class="star">*</span>来文标题</p>
                        <input type="text" placeholder="请填写来文标题" v-model="addFileForm.documentTitle">
                    </div>
                    <div class="input_box">
                        <p class="pTitle"><span class="star">*</span>接收时间</p>
                        <el-config-provider :locale="locale">
                            <el-date-picker v-model="addFileForm.receivedTime" type="date" placeholder="请选择接收时间"
                                @change="changeTime" class="timePicker"
                                style="width: 100%; height: 39px; background-color:red !important;  border-radius: 5px; outline:none !important;" />
                        </el-config-provider>
                    </div>
                </div>
                <div class="row flex">
                    <div class="input_box">
                        <p class="pTitle"><span class="star"></span>来文字号</p>
                        <input type="text" placeholder="请填写来文字号" v-model="addFileForm.documentNumber">
                    </div>
                    <div class="input_box">
                        <p class="pTitle"><span class="star">*</span>来文部门</p>
                        <input type="text" placeholder="请填写来文部门" v-model="addFileForm.department">
                        <div style="width: 100%;height: 20px;margin-top: 10px;">
                            <el-radio-group v-model="addFileForm.department">
                                <el-radio style="margin-right: 10px;" v-for="item in allFromDepartment"
                                    :key="item.department" :value="item.department" :label="item.department"></el-radio>
                            </el-radio-group>
                        </div>
                    </div>
                </div>
                <div class="row flex" style="height: auto !important;">
                    <div class="input_box">
                        <p class="pTitle"><span class="star">*</span>统筹人</p>

                        <!-- 校领导显示 -->
                        <div style="width: 100%;height: 20px;margin-top: 10px;">
                            <el-checkbox-group v-model="checkedTeacher1" @change="changeTeacher2">
                                <el-checkbox v-for="item in leaderList" :key="item.id" :value="item.value"
                                    :label="item.teacherName"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>

                </div>
                <div class="row flex">
                    <div class="input_box">
                        <p class="pTitle"><span class="star">*</span>主办处室</p>
                        <el-tree-select v-model="checkedDepart1" :data="departmentList" multiple size="large"
                            :class="{ 'select1': checkedDepart1.length <= 0, }" placeholder="请选择主办处室（可多选）"
                            ref="departmentSelect" :render-after-expand="false" show-checkbox @change="changeDepart1" />
                    </div>
                    <div class="input_box">
                        <p class="pTitle"><span class="star"></span>配合部门</p>
                        <el-tree-select v-model="checkedDepart2" :data="departmentList" multiple size="large"
                            :class="{ 'select1': checkedDepart1.length <= 0, }" placeholder="请选择配合部门（可多选）"
                            ref="departmentSelect1" :render-after-expand="false" show-checkbox
                            @change="changeDepart2" /> 
                    </div>
                </div>
                <div class="text_box">
                    <p class="pTitle">办公室拟办意见</p>
                    <textarea placeholder="请填写文字描述" v-model="addFileForm.documentDescription"></textarea>
                </div>

                <div class="text_box">
                    <p class="pTitle"><span class="star">*</span>上传文件</p>
                    <div id="dropzone" @dragover.prevent @drop="handleDrop" @click="handleFileClick"
                        class="dropzone flex">
                        <div class="flex">
                            <img src="../../assets/fileFlow_add.png" style="margin: 0 10px 0 20px;">
                            <p class="tip">拖拽或点击上传文件</p>
                        </div>
                        <input type="file" ref="fileInput" accept=".xlsx,.xls,.doc,.docx,.pdf" style="display: none;"
                            @change="handleFileSelect" />
                    </div>
                    <div class="file-list">
                        <div class="file_li" v-for="( file, index ) in  fileList   " :key="index">
                            <div class="fileBox">
                                <img src="../../assets/fileFlow_doc.png"
                                    v-if="['doc', 'docx', 'DOC', 'DOCX'].includes(file.suffix)">
                                <img src="../../assets/fileFlow_pdf.png" v-if="['PDF', 'pdf'].includes(file.suffix)">
                                <img src="../../assets/fileFlow_xls.png"
                                    v-if="['XLS', 'XLSX', 'xls', 'xlsx'].includes(file.suffix)">
                                <div>
                                    <p class="fileName">
                                        <el-text line-clamp="1" class="w-150px mb-2">{{ file.fileName
                                            }}</el-text>
                                    </p> 
                                </div>
                            </div>
                            <el-icon @click="delFileHandle(index)">
                                <Close />
                            </el-icon>
                        </div>
                    </div>
                </div>

                <div class="publishBox">
                    <button class="publish" v-loading.fullscreen.lock="fullscreenLoading" @click="publish">发布</button>
                </div>



            </div>
        </div>
    </myDialog>
</template>

<script>
import { ref } from "vue";
import addImageView from "@/components/addImage.vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm, ElLoading } from "element-plus";
import { formatTime } from "../../utils/dateFormat"
import { Close } from "@element-plus/icons-vue";
import { vxRule } from "@/utils/validator";
import myDialog from "../commonModule/myDialog.vue";
import zhCn from "element-plus/lib/locale/lang/zh-cn";

export default {
    name: "AddApp",
    components: { ElForm, addImageView, ElMessage, Close, myDialog, ElLoading },
    setup() {
        return {
            locale: zhCn,
        }
    },
    data() {
        return {
            // imgg: "http://192.168.9.20/upload/2024-09-23/1727053313205_surveybg.2b92f2fa.png",
            dialogFormVisible: ref(false),
            formLabelWidth: "120px",
            files: [], // 用于存储拖放的文件  
            dragOver: false, // 用于判断是否正在拖放文件上方  
            popupFlag: false,
            fileList: [
            ],
            fullscreenLoading: false,

            departmentList: [],
            teacherList: [],
            checkedTeacher1: [],
            checkedTeacher2: [],
            checkedDepart1: [],
            checkedDepart2: [],
            value1: "",
            teacherName: "",
            leaderList: [],

            teacherFlag: false,
            departmentFlag1: false,
            departmentFlag2: false,
            user: {},
            radio: [],
            allFromDepartment: [],
            allFromDepartmentChecked: [],
            addFileForm: {

                id: "",
                documentTitle: "",
                documentNumber: "",
                department: "",
                receivedTime: "",
                coordinator: "",
                mainOffice: "",
                cooperatingDepartment: "",
                documentDescription: "",
                filePath: "",
            },
            // 校验规则
            addApprules: {
                comeName: vxRule(true, null, "blur"),
                comedepartName: vxRule(true, null, "blur"),
                comeFontSize: vxRule(true, null, "blur"),
                cpmeTime: vxRule(true, null, "blur"),
                coordinator: vxRule(true, null, "blur"),
                departmentName1: vxRule(true, null, "blur"),
                departmentName2: vxRule(true, null, "blur"),
                remark: vxRule(true, null, "blur"),
                file: vxRule(true, null, "blur"),
            },


        };
    },
    mounted() {
        this.user = JSON.parse(sessionStorage.getItem('user'))
        this.getLeaderList()
        this.getDepartmentList()
        this.getAllFromDepartment()
        // this.getBaseTeacherList()
        this.addFileForm.receivedTime = formatTime(new Date())
    },
    computed: {
        filteredTeacherList() {
            if (this.teacherName) {
                return this.teacherList.filter(item =>
                    item.label.includes(this.teacherName)
                    // console.log(item.name, this.teacherName)
                );
            } else {
                return this.teacherList;
            }
        }
    },
    methods: {
        // javaApi/docDocuments/getAllFromDepartment 
        getAllFromDepartment() {
            httpService(
                "/javaApi/docDocuments/getAllFromDepartment", {}, "get"
            ).then((data) => {
                if (data.length > 0) {
                    this.allFromDepartment = data
                }
            });
        },


        queryById(id) {
            httpService("/javaApi/docDocuments/queryById", { id: id }, "get").then((data) => {
                this.addFileForm = data
                this.checkedTeacher1 = this.addFileForm.coordinator.split(",")
                if (this.addFileForm.mainOffice) {
                    this.checkedDepart1 = this.addFileForm.mainOffice.split(",")
                } else {
                    this.checkedDepart1 = []
                }
                if (this.addFileForm.cooperatingDepartment) {
                    this.checkedDepart2 = this.addFileForm.cooperatingDepartment.split(",")
                } else {
                    this.checkedDepart2 = []
                }
                if (this.addFileForm.filePath) {
                    this.fileList = this.addFileForm.filePath.split(',').map(item => {
                        return {
                            url: item,
                            fileName: item.split(/_(.*)/)[1],
                            suffix: item.split(".")[1],
                        }
                    })
                }
                const buttonElement = this.$refs.departmentSelect.$el;
                if (this.checkedDepart1.length > 0 && buttonElement) {
                    buttonElement.classList.add('select2');
                }
                const buttonElement1 = this.$refs.departmentSelect1.$el;
                if (this.checkedDepart2.length > 0 && buttonElement1) {
                    buttonElement1.classList.add('select2');
                }
            });
        },
        getLeaderList() {
            httpService(
                "/javaApi/baseTeacherDepartment/list/1/20",
                { departmentId: 105, }, "get"
            ).then((data) => {
                if (data.list) {
                    data.list.map(item => item.value = item.teacherNumber + '-' + item.teacherName)
                    this.leaderList = data.list
                }
            });
        },
        changeTeacher1(value) {
            this.teacherName = ""

            const buttonElement = this.$refs.departmentTeacher1.$el;
            if (this.checkedTeacher1.length > 0 && buttonElement) {
                buttonElement.classList.add('select2');
            } else {
                buttonElement.classList.remove('select2');
            }
            this.addFileForm.coordinator = this.checkedTeacher1.join(",")
        },
        changeTeacher2(value) {
            // console.log(this.checkedTeacher1);
            this.addFileForm.coordinator = this.checkedTeacher1.join(",")
            console.log(this.addFileForm.coordinator);
        },
        changeDepart1(value) {
            console.log(this.checkedDepart1);
            const buttonElement = this.$refs.departmentSelect.$el;
            if (this.checkedDepart1.length > 0 && buttonElement) {
                buttonElement.classList.add('select2');
            } else {
                buttonElement.classList.remove('select2');
            }
            this.addFileForm.mainOffice = this.checkedDepart1.join(",")
        },
        changeDepart2(value) {
            const buttonElement = this.$refs.departmentSelect1.$el;
            if (this.checkedDepart2.length > 0 && buttonElement) {
                buttonElement.classList.add('select2');
            } else {
                buttonElement.classList.remove('select2');
            }
            console.log(this.checkedDepart2);
            this.addFileForm.cooperatingDepartment = this.checkedDepart2.join(",")
        },

        closeHandle() {
            this.popupFlag = false
            this.clear()
        },
        closeDialog() {
            this.clear();
        },
        cancel() {
            this.dialogFormVisible = false;
            this.clear();
        },

        clear() {
            this.dialogFormVisible = false;

            this.addFileForm.documentTitle = ""
            this.addFileForm.documentNumber = ""
            this.addFileForm.department = ""
            this.addFileForm.receivedTime = ""
            this.addFileForm.coordinator = ""
            this.addFileForm.mainOffice = ""
            this.addFileForm.cooperatingDepartment = ""
            this.addFileForm.documentDescription = ""
            this.addFileForm.filePath = ""
            this.teacherName = ""
            this.$refs.fileInput.value = ''
            this.$refs.departmentSelect1.blur()
            this.$refs.departmentSelect.blur()
            // this.$refs.departmentTeacher1.blur()

            this.fileList = []
            this.checkedTeacher1 = []
            this.checkedDepart1 = []
            this.checkedDepart2 = []

        },
        changeTime(value) {
            this.addFileForm.receivedTime = formatTime(value)
        },
        convertSize(bytes) {
            const KB = 1024;
            const MB = KB * 1024;
            if (bytes < MB) {
                return `${(bytes / KB).toFixed(2)} KB`;
            } else {
                return `${(bytes / MB).toFixed(2)} MB`;
            }
        },
        publish() {
            console.log(this.checkedTeacher1);
            if (!this.addFileForm.documentTitle) {
                ElMessage.error("请填写来文标题");
            }
            //  else if (!this.addFileForm.documentNumber) {
            //     ElMessage.error("请填写来文字号");
            // }
            else if (!this.addFileForm.receivedTime) {
                ElMessage.error("请选择接收时间");
            } else if (!this.addFileForm.department) {
                ElMessage.error("请填写来文部门");
            } else if (this.checkedTeacher1.length <= 0) {
                ElMessage.error("请选择统筹人");
            } else if (this.checkedDepart1.length <= 0) {
                ElMessage.error("请选择主办处室");
            }
            // else if (this.checkedDepart2.length <= 0) {
            //     ElMessage.error("请选择配合部门");
            // }
            // else if (!this.addFileForm.documentDescription) {
            //     ElMessage.error("请填写文字描述");
            // } 
            else if (this.fileList.length <= 0) {
                ElMessage.error("请选择上传文件");
            } else {
                this.fullscreenLoading = true;
                const fileAll = this.fileList.map(item => item = item.url).join(',')
                let names = this.checkedTeacher1.join(",")
                let params = new FormData();
                params.append("documentTitle", this.addFileForm.documentTitle);
                params.append("documentNumber", this.addFileForm.documentNumber);
                params.append("department", this.addFileForm.department);
                params.append("receivedTime", this.addFileForm.receivedTime);
                params.append("coordinator", names);
                params.append("mainOffice", this.addFileForm.mainOffice);
                params.append("cooperatingDepartment", this.addFileForm.cooperatingDepartment);
                params.append("documentDescription", this.addFileForm.documentDescription);
                params.append("status", "pending_principal");
                params.append("filePath", fileAll);
                // return
                if (this.addFileForm.id) {
                    params.append("id", this.addFileForm.id);
                    httpService("/javaApi/docDocuments/edit", params, "post").then((data) => {
                        this.fullscreenLoading = false

                        if (data.code == 200) {
                            ElMessage.success("修改成功");
                            this.clear();
                            this.closeHandle()
                            this.$parent.getFileList();
                        } else {
                            ElMessage.error("修改失败");
                        }
                    });
                } else {
                    httpService("/javaApi/docDocuments/add", params, "post").then((data) => {
                        this.fullscreenLoading = false

                        if (data.code == 200) {
                            ElMessage.success("发布成功");
                            this.clear();
                            this.closeHandle()
                            this.$parent.getFileList();
                        } else {
                            ElMessage.error("发布失败");
                        }
                    });
                }

            }
        },

        handleFileClick() {
            this.$refs.fileInput.click();
        },

        handleFileSelect(event) {
            const file = event.target.files[0];
            let params = new FormData()
            params.append("file", file)
            httpService(
                "/javaApi/upload/uploadFile", params, "post"
            ).then((data) => {
                console.log(data);
                this.fileList.push({
                    url: data.url,
                    fileName: data.title,
                    suffix: data.url.split(".")[1],
                })
            });
        },

        handleDrop(event) {
            event.stopPropagation();
            event.preventDefault();
            const files = event.dataTransfer ? event.dataTransfer.files : [];
            if (files.length > 0) {
                this.fileList.push(files[0])
            }
        },

        delFileHandle(index) {
            this.fileList.splice(index, 1)
            console.log(this.fileList);
        },

        getDepartmentList() {
            let num = 1
            this.user.campus == 1 ? num = 1 : num = 2
            httpService("/javaApi/baseDepartment/list/1/100", { parentId: num, }, "get").then(
                (data) => {
                    if (data.list) {
                        this.departmentList = data.list.filter(item => (item.type == 1 || item.type == 2) && item.name != '校领导' && item.name != '体艺卫' && item.name != '体育组' && item.name != '纪检室')

                        this.departmentList = this.departmentList.map(item => {
                            return { label: item.name, value: item.id + '-' + item.name }
                        })
                    }
                }
            );
        },

        // getBaseTeacherList() {
        //     httpService(
        //         "/javaApi/baseTeacher/list/1/10000", {}, "get"
        //     ).then((data) => {
        //         if (data.list) {
        //             this.teacherList = data.list.map(item => {
        //                 return { label: item.name, value: item.teacherNumber + '-' + item.name, id: item.id }
        //             })
        //         }
        //     });
        // },
        inputHandle() {
            console.log(this.teacherName);
        },
    }

};
</script>
<style scoped>
* {
    margin: 0;
    padding: 0;
}

.flex {
    display: flex;
    align-items: center;
}



.main {
    width: 80vw;
    max-width: 1336px;
    min-width: 500px;
    /* min-height: 800px; */
    background-color: #fff;
    border-radius: 5px;
    padding: 15px 15px 30px;
}

.header {
    justify-content: space-between;
    margin-bottom: 30px;
}

.header .el-icon {
    margin-right: 20px;
}

.title_box {
    color: #000;
    font-size: 21px;
    font-weight: bold;
    letter-spacing: 1px;
    /* margin-bottom: 40px; */
}

.input_box {
    width: calc((100% - 40px) / 2);
}

.pTitle {
    color: #000;
    font-size: 15px;
    margin-bottom: 10px;
}


.input_box input {
    width: calc(100% - 22px);
    border: 1px solid #E6E6E6;
    outline: none;
    background-color: #F5F5F5;
    height: 37px;
    font-size: 13px;
    color: #000;
    font-size: 13px;
    padding: 0 10px;
    border-radius: 5px;
}

.input_box input::placeholder {
    color: #999999;
}

.input_box .el-select {
    width: 100%;
    height: 37px;
}

.row {
    margin-top: 20px;
    justify-content: space-between;
    min-height: 50px;
}

.text_box {
    margin-top: 30px;
}

.text_box textarea {
    width: calc(100% - 20px);
    height: 80px;
    padding: 12px 10px;
    resize: none;
    outline: none;
    border: 1px solid #E6E6E6;
    border-radius: 5px;
}

.upload-demo {
    height: 50px;
}

.el-upload {
    height: 50px;
}

.el-upload-dragger {
    border: 1px solid #E6E6E6;
    height: 50px;
}

.dropzone {
    border: 1px solid #E6E6E6;
    height: 50px;
    border-radius: 5px;
}

.tip {
    color: #000;
    font-size: 13px;
}

.publishBox {
    margin: 40px 0 0;
    text-align: center;
}

.publish {
    width: 130px;
    height: 40px;
    background-color: #007EFF;
    border-radius: 5px;
    border: none;
    color: #fff;
    font-size: 17px;
    border: none;
}

.select ::v-deep .el-tooltip__trigger {
    /* height: 37px; */
    width: 100%;
}

.select1 ::v-deep .el-tooltip__trigger {
    /* height: 37px; */
    background-color: #F5F5F5;
    width: 100%;
}

.select2 ::v-deep .el-tooltip__trigger {
    background-color: #fff;
    width: 100%;
}

.el-select-dropdown__item {
    padding-left: 15px;
}

.el-select {
    --el-color-primary: #FF7404;
}


.el-tooltip__trigger {
    height: 37px;
    background-color: #9b2f2f;
}






.file-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    column-gap: 30px;
}

.file_li {
    height: 75px;
    line-height: 30px;
    background-color: #F1F3F5;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    border-radius: 5px;
}

.fileBox {
    display: flex;
    align-items: center;
}

.file_li img {
    margin-left: 14px;
    margin-right: 8px;
}

.file_li .el-icon {
    margin-right: 36px;
}


.fileName {
    color: #000000;
    font-size: 13px;
    line-height: 13px;
}

.fileSize {
    color: #999999;
    font-size: 13px;
    line-height: 13px;
    margin-top: 6px;
}


/* 修改日期选择器的样式 */
::v-deep .el-date-editor {
    --el-fill-color-blank: #F5F5F5 !important;
    --el-color-primary: #FF7404;
}

.star {
    color: #FF0000;
}


::v-deep .el-tag {
    background-color: #007EFF;
    color: #fff;
}

::v-deep .el-tag .el-icon {
    color: #FFF;
}

::v-deep .el-radio__label {
    padding-left: 4px !important;
}

.el-checkbox {
    margin-right: 10px;
    height: 20px;
}

::v-deep .el-checkbox__label {
    padding-left: 4px !important;
}
</style>
